<?php

namespace addons\tools\controller\api\v1;

use addons\oss\library\Qiniu;
use addons\tools\library\AipBase;
use addons\tools\library\AipHttpClient;
use addons\tools\library\Service;
use addons\tools\model\MealLog;
use addons\tools\model\UserVipLog;
use addons\tools\model\UserVipRule;
use addons\tools\model\UserVipRuleLog;
use app\common\controller\Api;
use addons\tools\model\Tools as ToolsModel;
use think\Db;
use think\Exception;
use AlibabaCloud\SDK\ViapiUtils\ViapiUtils;

class Tools extends Api
{

    protected $noNeedLogin = ['index', 'detail', 'hot', 'synthesis','imgConvert'];

    protected $noNeedRight = ['*'];


    public function index()
    {
        $toolsModel = new ToolsModel();
        $list = $toolsModel->getLists($this->request->param());
        $this->success(__('获取数据成功'), $list);
    }

    public function detail()
    {
        $id = $this->request->get('id', 0);
        if (!$id)
            $this->error('参数错误');
        $toolsModel = new ToolsModel();
        $detail = $toolsModel->getDetailById($id)->hidden(['font_ids', 'font1_ids']);
        if (!$detail)
            $this->error('数据不存在');
        $this->success(__('获取数据成功'), $detail);
    }

    public function hot()
    {
        $toolsModel = new ToolsModel();
        $list = $toolsModel->field('id,name,images')->where('find_in_set(:flag,flag)', ['flag' => 'hot'])->where('status', 'normal')->order('weigh', 'DESC')
            ->order('create_time', 'desc')->select();
        $this->success(__('获取数据成功'), $list);

    }

    public function synthesis()
    {

        $params = $this->request->post();
        if (empty($params['tool_id'])) $this->error(__('参数错误'));
        $toolDetail = (new ToolsModel())->getDetailById($params['tool_id']);
        if (!$toolDetail) $this->error(__('工具不存在或已下架'));
        $header = [
            'Host'       => '2.84c.cn',
            'Origin'     => 'http://2.84c.cn',
            'Referer'    => 'http://2.84c.cn/b/m27.htm',
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36'
        ];
        $aipHttp = new AipBase($header);

        $rest = $aipHttp->request(array_merge([
            'id8'    => 'jiqie',
            'zhenbi' => 20191123,
        ], $params), $toolDetail->page, $toolDetail->file);
        if (!empty($rest['zhenbi'])) {
            $qiniu = new Qiniu();
            try {
                $ret = $qiniu->fetch($rest['zhenbi'][0]['info'][0], '.jpg');
                $this->success(__('合成成功'), $ret);
            } catch (Exception $exception) {
                $this->error($exception->getMessage());
            }
        }
        $this->error(__('生成失败'));
    }

    public function aiBoot()
    {
        if ($this->request->isGet())
            $this->error('请求错误', [], 405);
        $params = $this->request->post();
        if (empty($params['tool_id'])) $this->error(__('参数错误'));
        $toolId = $params['tool_id'];
        $toolDetail = (new ToolsModel())->getDetailById($toolId);
        if (!$toolDetail) $this->error(__('工具不存在或已下架'));
        $userInfo = \addons\tools\model\User::with([
            'userVip'     => function ($query) {
                $query->field('user_id,validity_time');
            },
            'userVipRule' => function ($query) {
                $query->field('user_id,id,tool_id,value as number');
            }])->where('id', $this->auth->id)->find();
        $userVipRule = $userInfo->userVipRule;
        if (empty($userVipRule))
            $this->error('无权使用，请联系管理员', null, 2);
        $vipRuleArr = [];
        foreach ($userVipRule as $k => $v) {
            $vipRuleArr[$v['tool_id']] = $v->toArray();
        }
        if (!isset($vipRuleArr[$toolId])) {
            $this->error('您暂未购买该工具的使用次数');
        }
        if ($vipRuleArr[$toolId]['value'] == 0) {
            $this->error('工具使用次数已用完', null, 2);
        }
        $ossUrl = ViapiUtils::upload('LTAI5tDu1JeoFc76HKGH7U1m', 'q6TnuHHqspa3Xo8pDQFOLhIcnnUnx5', htmlspecialchars_decode($params['ImageURL']));
        $params['ImageURL'] = $ossUrl;
        $category = $toolDetail->category;
        $categoryCode = '';
        if ($category) {
            $categoryCode = $category->code;
        }
        if (!$categoryCode)
            $this->error('参数错误');
        $service = new Service();
        $rest = $service->synthesis($params, $toolDetail->source, $toolDetail->code);
        if ($rest['code'] !== 200) {
            $content = json_decode($rest['content'], true);
            $this->error($content['Message']);
        }
        $userVipRuleModel = new UserVipRule();

        $ruleModel = $userVipRuleModel->where('user_id', $this->auth->id)
            ->where('tool_id', $toolId)->find();
        $ruleModel->value = $ruleModel->value - 1;
        $ruleModel->save();
        $userVipRuleLog = new UserVipRuleLog();
        $userVipRuleLog->save([
            'user_id' => $this->auth->id,
            'title'   => '使用<' . $vipRuleArr[$toolId]['tool_name'] . '>工具，扣除1次次数',
            'value'   => 1
        ]);
        $this->success(__('成功'), json_decode($rest['content'], true));
    }

    public function useMeal()
    {
        Db::transaction(function () {
            try {
                $user = $this->auth->getUser();
                $logData = [
                    'user_id' => $this->auth->id,
                    'number'  => 1,
                    'before'  => $user['tools_use_num'],
                    'after'   => $user['tools_use_num'] - 1,
                    'memo'    => '使用工具-1次'
                ];
                $user->tools_use_num = $user->tools_use_num - 1;
                $user->save();
                MealLog::createLog($logData);
                return true;
            } catch (Exception $exception) {
                $this->error($exception->getMessage());
            }
        });
        $this->success('记录成功');

    }

    /**
     * 图片转换
     * @return void
     */
    public function imgConvert()
    {
        header("Content-type:image/jpeg");
        $url = $this->request->get('url');
        if (!$url)
            $this->error('参数错误');
        $url = htmlspecialchars_decode($url);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 0);
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 3);//超过3秒不处理
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //执行之后信息以文件流的形式返回
        $file = curl_exec($ch);
        echo $file;die();
    }

}